﻿using System.Linq;
using System.Web.Mvc;
using BusinessLibrary;
using MMSWebsite.DataAccessManagement;
using MMSWebsite.HtmlHepler;
using MMSWebsite.Models;

namespace MMSWebsite.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/
        EmployeeAccessProvider _empProvider = new EmployeeAccessProvider();
        MMSEntities entities = new MMSEntities();


        public ActionResult Search(string keyName, string keyCode, string keyCity, string keyDistrict, string keyRole, bool keyIsLocked, bool keyIsActive)
        {
            var emps = _empProvider.GetAllEmployee();
            if(keyName != "") emps = emps.Where(x => x.Employee.Name.ToLower().Contains(keyName.ToLower())).ToList();
            if (keyCode != "") emps = emps.Where(x => x.Employee.Code.Contains(keyCode)).ToList();
            if (keyCity != "") emps = emps.Where(x => x.Employee.Area.CityName == keyCity).ToList();
            if (keyDistrict != "") emps = emps.Where(x => x.Employee.Area.DistrictName == keyDistrict).ToList();
            if (keyRole != "") emps = emps.Where(x => x.Roles.Any(r => r.Role.RoleName == keyRole && r.RoleIsChecked == true)).ToList();
            if (keyIsLocked) emps = emps.Where(x=>x.Employee.IsLocked == true).ToList();
            if (keyIsActive) emps = emps.Where(x => x.Employee.IsLocked == false).ToList();

            //var emps = _empProvider.GetAllEmployee();
            return PartialView("ListEmployeePartial", emps);
        }

        //[MyAuthorize(Roles = "Admin_TPHCM,Admin_HaNoi")]
        public ActionResult Index()
        {
            SetViewBagData(null);
            var emps = _empProvider.GetAllEmployee();
            return View(emps);
        }

        //
        // GET: /Employee/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Employee/Create
        //Get List Districts belong to city
        //return 1 file Json with 1 field DistrictName
        public JsonResult DistrictList(string city)
        {
            var items = entities.MMS_AREAs.Where(d => d.CityName == city).OrderBy(x=>x.DistrictName).Select(c => new
                                                                                     {
                                                                                         DistrictName = c.DistrictName
                                                                                     });
            return Json(items, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            SetViewBagData(null);
            var emp = new EmployeeViewModel
                                        {
                                            Employee =
                                                new Employee
                                                    {
                                                        Code =
                                                            CodeGenerator.AutoGenerateCode(
                                                                entities.MMS_EMPLOYEEs.ToList().Last().Id.ToString())
                                                    }
                                        };

            return View(emp);
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        public ActionResult Create(EmployeeViewModel emp, FormCollection collection)
        {
            SetViewBagData(null);
            if (!ModelState.IsValid)
            {
                return View(emp);
            }
            else
            {
                // TODO: Add insert logic here
                //emp.Employee.Password = MD5Security.GetMd5Hash(md5hash, CodeGenerator.AutoGeneratePass(5));
                foreach (var role in emp.Roles.Where(role => collection[role.Role.RoleName] == "on"))
                {
                    role.RoleIsChecked = true;
                }
                emp.Employee.IsLocked = false;

                //generate password
                string randompass = CodeGenerator.AutoGeneratePass(5);
                WebMailHelper.SendPassword(emp.Employee.Email, emp.Employee.Name, emp.Employee.Code, randompass);
                //enscrypt and save db
                emp.Employee.Password = MD5Security.GetMd5Hash(randompass);
                _empProvider.AddEmployee(emp);
                return RedirectToAction("Index");
            }
        }

        public ActionResult ResetPassword(int id)
        {
            _empProvider.ResetPassword(id);
            var emp = _empProvider.GetEmployeeById(id);
            return View("ResetPassSuccessfully", emp);
        }

        //
        // GET: /Employee/Edit/5

        public ActionResult Edit(int id)
        {
            SetViewBagData(id);
            var emp = _empProvider.GetEmployeeById(id);
            return View(emp);
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection collection, EmployeeViewModel emp)
        {
            
            if (!ModelState.IsValid)
            {
                return View(emp);
            }
            else
            {
                // TODO: Add update logic here
                foreach (var role in emp.Roles.Where(role => collection[role.Role.RoleName] == "on"))
                {
                    role.RoleIsChecked = true;
                }

                _empProvider.UpdateEmployee(emp);
                return RedirectToAction("Index");
            }
        }

        public ActionResult TriggerLock(int id)
        {
            _empProvider.TriggerLock(id);
            return RedirectToAction("Edit", "Employee", new {id = id});
        }

        public void SetViewBagData(int? id)
        {
            ViewBag.Roles = entities.MMS_ROLEs.Select(r => r.RoleName).Distinct();
            ViewBag.Cities = entities.MMS_AREAs.Select(c => c.CityName).Distinct();
            ViewBag.Districts = entities.MMS_AREAs.Select(d => d.DistrictName);
            if (id != null)
            {
                var emp = entities.MMS_EMPLOYEEs.FirstOrDefault(c => c.Id == id);
                if (emp.MMS_AREA != null)
                {
                    ViewBag.Districts =
                        entities.MMS_AREAs.Where(d => d.CityName == emp.MMS_AREA.CityName).Select(
                            d => d.DistrictName);
                }
            }

            //set name of form Search (SearchViewPartial)
            ViewBag.NameSearch = "Search";
        }
    }
}
